package v1

import (
	"RoccBlog/global"
	"RoccBlog/model"
	"RoccBlog/model/req_resp"
	v1 "RoccBlog/repository/v1"
	"RoccBlog/service"
	"RoccBlog/util"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
)

type PermissionService struct {
	service.BaseOperationService
	service.BaseService
	Repository v1.PermissionRepository
}

func init() {
	global.RegisterService(&PermissionService{})
}

func (s *PermissionService) Add(ctx *gin.Context, data model.Permission) error {
	return s.Repository.Create(data)
}

func (s *PermissionService) Remove(ctx *gin.Context, id int) error {
	return s.Repository.Delete(id)
}

func (s *PermissionService) Modify(ctx *gin.Context, data model.Permission) error {
	return s.Repository.Update(data)
}

func (s *PermissionService) FindById(ctx *gin.Context, id int) (model.Permission, error) {
	return s.Repository.SelectById(id)
}

func (s *PermissionService) Find(ctx *gin.Context) (any, error) {

	// 获取数据
	size, num := s.GetPage(ctx)
	pageInfo, err := s.Repository.Select(num, size)
	list := pageInfo.(util.PageInfo).List.([]model.Permission)

	//数据只有1条不进行
	if pageInfo.(util.PageInfo).Total < 2 {
		return pageInfo, err
	}

	// 转换为树形结构
	childMap := make(map[int]*req_resp.PermissionResp)
	permissionRespList := make([]*req_resp.PermissionResp, 0)
	for _, val := range list {

		// 拷贝值
		permissionResp := req_resp.PermissionResp{}
		copier.Copy(&permissionResp, &val)

		// 将没有上级ID的添加到切片中
		if val.ParentId == 0 {
			permissionRespList = append(permissionRespList, &permissionResp)
		}

		// 记录到map中
		childMap[permissionResp.Id] = &permissionResp
	}

	for _, val := range childMap {

		//没有父级，比成绩
		if val.ParentId == 0 {
			continue
		}

		// 有父级id记录但是没有存在这个父级，则添加到一级中
		_, ok := childMap[val.ParentId]
		if !ok {
			permissionRespList = append(permissionRespList, val)
			continue
		}

		// 第一次是空
		if childMap[val.ParentId].Children == nil {
			childMap[val.ParentId].Children = make([]req_resp.PermissionResp, 0)
		}

		// 添加到 children中
		childMap[val.ParentId].Children = append(childMap[val.ParentId].Children, *val)
	}

	// 重新赋值
	info := pageInfo.(util.PageInfo)
	info.List = permissionRespList

	return info, err
}

func (s *PermissionService) FindByIds(ids []int) ([]model.Permission, error) {
	return s.Repository.SelectByIds(ids)
}
